<template>
  <div>
    <page-container title="基本资料">
      <template #form>
        <el-form
          label-width="120px"
          ref="userFormRef"
          :rules="userFormRules"
          :model="formData"
          v-loading="loading">
          <el-form-item label="登录名称">
            <el-input disabled v-model="formData.username" />
          </el-form-item>
          <el-form-item label="用户昵称" prop="nickname">
            <el-input v-model="formData.nickname" />
          </el-form-item>
          <el-form-item label="用户邮箱" prop="email">
            <el-input v-model="formData.email" />
          </el-form-item>
          <el-form-item>
            <el-button @click="onSubmit">提交修改</el-button>
          </el-form-item>
        </el-form>
      </template>
    </page-container>
  </div>
</template>
<script setup>
  import { ref } from 'vue';
  // pinia中数据
  import { useUserStore } from '@/stores/user.js';
  const userStore = useUserStore();
  const formData = ref({
    id: userStore.user.id,
    username: userStore.user.username,
    nickname: userStore.user.nickname,
    email: userStore.user.email
  });
  const userFormRules = {
    nickname: [
      { required: true, message: '昵称不能为空', trigger: 'blur' },
      { min: 2, max: 10, message: '长度在 2 到 10 个字符', trigger: 'blur' }
    ],
    email: [
      { required: true, message: '邮箱不能为空', trigger: 'blur' },
      {
        pattern:
          /^[A-Za-z0-9\u4e00-\u9fa5]+@[a-zA-Z0-9_-]+(\.[a-zA-Z0-9_-]+)+$/,
        message: '邮箱格式不正确',
        trigger: 'blur'
      }
    ]
  };
  const userFormRef = ref(null);
  const loading = ref(false);

  import { updateUserInfoApi } from '@/api/user.js';

  const onSubmit = async () => {
    loading.value = true;

    userFormRef.value.validate(async (valid, fields) => {
      if (valid) {
        const res = await updateUserInfoApi(formData.value);
        console.log(res, 'res');
        loading.value = false;
        if (res.code == 0) {
          ElMessage.success(res.message);
          userStore.getUser();
        } else {
          ElMessage.error(res.message);
        }
      } else {
        loading.value = false;
      }
    });
  };
</script>
<style lang="less" scoped>
  .el-input {
    width: 30%;
  }

  .el-button {
    background-color: #263f35;
    color: #fff;
  }
</style>
